<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select v-model="q.cate_id" placeholder="请选择分类" size="small">
              <el-option v-for="item in cateList" :key="item.id" :label="item.cate_name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px">
            <el-select v-model="q.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="search">筛选</el-button>
            <el-button type="info" size="small" @click="reset">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button type="primary" size="small" class="btn-pub" @click="showPubDialog">发表文章</el-button>
      </div>

      <!-- 文章表格区域 -->
      <el-table :data="artList" style="width: 100%" border stripe>
        <el-table-column label="文章标题">
          <template v-slot="obj">
            <el-link type="primary" @click="showDetail(obj.row.id)">{{ obj.row.title }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="分类" prop="cate_name"></el-table-column>
        <el-table-column label="发表时间">
          <template v-slot="obj">{{ obj.row.pub_date | dataFormat }}</template>
        </el-table-column>
        <el-table-column label="状态" prop="state"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="obj">
            <el-button type="danger" size="mini" @click="remove(obj.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <!-- current-page当前页码值1 -->
      <!-- page-size当前每页显示几条数据 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="q.pagenum"
        :page-sizes="[2, 3, 5, 10]"
        :page-size="q.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 发布文章的对话框 -->
    <el-dialog
      title="发表文章"
      :visible.sync="pubDialogVisible"
      :before-close="handleClose"
      fullscreen
      @closed="onDialogClosed"
    >
      <!-- 发布文章的对话框内容 -->
      <el-form :model="pubForm" :rules="pubFormRules" ref="pubFormRef" label-width="100px">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="pubForm.title" placeholder="请输入标题" maxlength="30"></el-input>
        </el-form-item>
        <el-form-item label="文章分类" prop="cate_id">
          <el-select v-model="pubForm.cate_id" placeholder="请选择分类" style="width: 100%">
            <!-- 展示的是label 数据收集的是value -->
            <el-option :label="item.cate_name" :value="item.id" v-for="item in cateList" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <!-- 富文本 -->
        <el-form-item label="文章内容">
          <!-- 使用 v-model 进行双向的数据绑定 -->
          <quill-editor v-model="pubForm.content"></quill-editor>
        </el-form-item>
        <!-- 文章封面 -->
        <el-form-item label="文章封面">
          <!-- 用来显示封面的图片 -->
          <img src="../../../assets/images/cover.jpg" alt="" class="cover-img" ref="imgRef" />
          <br />
          <!-- 文件选择框，默认被隐藏 -->
          <input type="file" style="display: none" accept="image/*" ref="iptFile" @change="onCoverChange" />
          <!-- 选择封面的按钮 -->
          <el-button type="text" @click="chooseImg">+ 选择封面</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="pwdArticle('已发布')">发布</el-button>
          <el-button type="info" @click="pwdArticle('草稿')">存为草稿</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 文章详情对话框 -->
    <el-dialog title="文章预览" :visible.sync="detailVisible" width="80%">
      <h1 class="title">{{ artDetail.title }}</h1>

      <div class="info">
        <span>作者：{{ artDetail.nickname || artDetail.username }}</span>
        <span>发布时间：{{ artDetail.pub_date | dataFormat }}</span>
        <span>所属分类：{{ artDetail.cate_name }}</span>
        <span>状态：{{ artDetail.state }}</span>
      </div>

      <!-- 分割线 -->
      <el-divider></el-divider>

      <img :src="'http://www.liulongbin.top:3008' + artDetail.cover_img" alt="" />

      <div v-html="artDetail.content"></div>
    </el-dialog>
  </div>
</template>

<script>
// 把图片以模块形式导入
import dafaultImg from '@/assets/images/cover.jpg'
export default {
  name: 'ArtList',
  data() {
    return {
      // 文章列表数据
      artList: [],
      // 总数据条数,实现分页
      total: 0,
      // 文章分类
      cateList: [],
      // 控制发布文章的对话框的显示与隐藏
      pubDialogVisible: false,
      pubForm: {
        title: '',
        cate_id: '',
        // 文章内容
        content: '',
        // 封面图片
        cover_img: null,
        // 发布状态
        state: ''
      },
      pubFormRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { pattern: /^.{1,30}$/, message: '文章标题的长度为1~30个字符', trigger: 'blur' }
        ],
        cate_id: [{ required: true, message: '请输入文章标题', trigger: 'change' }]
      },
      // 查询参数对象
      q: {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      },
      // 储存文章显示的数据
      artDetail: {},
      // 控制文章详情对话框的显示与隐藏
      detailVisible: false
    }
  },
  created() {
    this.initCateList()
    this.initArtList()
  },
  methods: {
    // 发布文章对话框显示
    showPubDialog() {
      this.pubDialogVisible = true
    },
    // 关闭对话框询问
    async handleClose(done) {
      const confirmResult = await this.$confirm('此操作将导致文章信息丢失, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => error)
      if (confirmResult === 'cancel') return
      done(true)
    },
    // 添加文章弹出框的初始化文章分类的列表数据
    async initCateList() {
      const { data: res } = await this.$http.get('/my/cate/list')
      if (res.code === 0) {
        this.cateList = res.data
      }
    },
    chooseImg() {
      this.$refs.iptFile.click()
    },
    // 封面
    onCoverChange(e) {
      const files = e.target.files
      if (files.length === 0) {
        this.pubForm.cover_img = null
        this.$refs.imgRef.setAttribute('src', dafaultImg)
      } else {
        this.pubForm.cover_img = files[0]
        const url = URL.createObjectURL(files[0])
        this.$refs.imgRef.setAttribute('src', url)
      }
    },
    // 发布状态
    pwdArticle(state) {
      this.pubForm.state = state
      // 预验证
      this.$refs.pubFormRef.validate(async valid => {
        if (!valid) return
        if (this.pubForm.content === '') return this.$message.error('请填写文章内容')
        if (this.pubForm.cover_img === null) return this.$message.error('请选择文章封面')
        // console.log(this.pubForm)
        // 发布文章
        const fd = new FormData()
        for (const k in this.pubForm) {
          fd.append(k, this.pubForm[k])
        }
        // 调用接口
        const { data: res } = await this.$http.post('/my/article/add', fd)
        if (res.code !== 0) return this.$message.error('发表文章失败')
        this.$message.success('发表文章成功')
        this.pubDialogVisible = false
        // 刷新文章的列表信息
        this.initArtList()
      })
    },
    // 关闭时数据清除
    onDialogClosed() {
      this.$refs.pubFormRef.resetFields()
      this.pubForm.content = ''
      this.pubForm.cover_img = null
      this.pubForm.state = ''
      this.$refs.imgRef.setAttribute('src', dafaultImg)
    },
    // 初始化文章列表数据
    async initArtList() {
      const { data: res } = await this.$http.get('/my/article/list', {
        params: this.q
      })
      if (res.code !== 0) return this.$message.error('获取文章数据失败')
      // 数据转存到data中
      this.artList = res.data
      this.total = res.total
    },
    // 每页显示几条数据变化时触发
    handleSizeChange(newSize) {
      this.q.pagesize = newSize
      this.pagenum = 1
      this.initArtList()
    },
    // 页码值变化触发
    handleCurrentChange(newPage) {
      this.q.pagenum = newPage
      this.initArtList()
    },
    // 筛选
    search() {
      this.initArtList()
    },
    // 重置
    reset() {
      this.q = {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      }
      this.initArtList()
    },
    // 展示文章详情
    async showDetail(id) {
      const { data: res } = await this.$http.get('/my/article/info', { params: { id } })
      if (res.code !== 0) return this.$message.error('获取文章详情失败')
      this.artDetail = res.data
      this.detailVisible = true
    },
    // 点击删除
    async remove(id) {
      const result = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => error)
      if (result === 'cancel') return
      const { data: res } = await this.$http.delete('/my/article/info', { params: { id } })
      if (res.code !== 0) return this.$message.error('删除失败')
      if (this.artList.length === 1 && this.q.pagenum > 1) {
        this.q.pagenum--
      }
      this.$message.success('删除成功')
      this.initArtList()
    }
  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}
// 设置富文本编辑器的默认最小高度
/deep/ .ql-editor {
  min-height: 300px;
}
// 设置图片封面的宽高
.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}
.el-pagination {
  margin-top: 15px;
}
.title {
  font-size: 24px;
  text-align: center;
  font-weight: normal;
  color: #000;
  margin: 0 0 10px 0;
}

.info {
  font-size: 12px;
  span {
    margin-right: 20px;
  }
}
/deep/.el-dialog__body {
  img {
    width: 400px;
    height: 300px;
  }
}
</style>
